//是否开始采集
var startCollectState = false;
$("#start").on('click', function () {
    if (!checkDataBaseState()) {
        return;
    }
    if (startCollectState == true) {
        var index = layer.confirm('您确定要停止采集吗？', { icon: 3 }, function () {
            window.formium.postMessage("Collect", "stop");
            layer.close(index);
        });
    }
    else {
        var index = layer.confirm('点击确定开始采集', { icon: 3 }, function () {
            window.formium.postMessage("Collect", "start");
            layer.close(index);
        });
    }
})

//开始采集
function startCollect() {
    $("#startBtn").text("停止采集");
    startCollectState = true;
    updateChartOption();
}

//停止采集
function stopCollect() {
    $("#startBtn").text("开始采集");
    startCollectState = false;
    clearInterval(chartInterval);
    $("#report").removeClass("layui-hide");
    $("#report").addClass('')
}

//测压报告
$("#report").on('click', function () {
    if (!checkDataBaseState()) {
        return;
    }
    getChartImageData()
    var index = layer.confirm('您确定要停止采集，生产试压报告吗？', { icon: 3 }, function () {
        layer.close(index);
        setTimeout(() => {
            window.formium.postMessage("Report", chartImageData);
        }, 300);
    });
})

//选择工程
$("#project").on('click', function () {
    if (!checkDataBaseState()) {
        return;
    }
    if (checkStartState()) {
        return;
    }
    window.formium.postMessage("ShowForm", "Project");
})

//添加模板
$("#template").on('click', function () {
    if (!checkDataBaseState()) {
        return;
    }
    if (checkStartState()) {
        return;
    }
    window.formium.postMessage("ShowForm", "Template");
})

//设置面板
$("#set").on('click', function () {
    if (!checkDataBaseState()) {
        return;
    }
    if (checkStartState()) {
        return;
    }
    window.formium.postMessage("ShowForm", "Operation");
})

//检查数据库状态
function checkDataBaseState() {
    if (dataBaseState == false) {
        layerMessage("数据库连接失败，无法操作", 2);
    }
    return dataBaseState;
}

//检查开始采集状态
function checkStartState() {
    if (startCollectState == true) {
        layerMessage("已开始采集，无法操作", 2);
    }
    return startCollectState;
}

///更新项目信息
function updateProjectInfo(number, name) {
    $("#project_title").text(name);
}

///更新累计时间
function updateTotalTime(time) {
    $("#total_time").text(time);
}

///更新近端信息
function updateMainInfo(info) {
    const object = JSON.parse(info);
    mediumTemplature = object.mediumTemplature;
    enviromentTemplature = object.enviromentTemplature;
    mainMachineTemplature = object.machineTemplature;
    $("#mtemplature").text(mediumTemplature);
    $("#etemplature").text(enviromentTemplature);
    $("#mmachinetemplature").text(mainMachineTemplature);
}

///更新远端信息
function updateRemoteInfo(info) {
    const object = JSON.parse(info);
    remoteMachineTemplature = object.machineTemplature;
    $("#rmachinetemplature").text(remoteMachineTemplature);
}

///更新近端压力
function updateMainPressure(value, alarm) {
    mainPressure = value;
    console.log(value);
    updatePressure("#mpressure", value, alarm)
}

///更新近端压力
function updateRemotePressure(value, alarm) {
    remotePressure = value;
    console.log(value);
    updatePressure("#rpressure", value, alarm)
}

///更新压力
function updatePressure(id, value, alarm) {
    $(id).text(value);
    if (alarm == 1) {
        $(id).addClass('layui-font-red')
    }
    else {
        $(id).removeClass('layui-font-red')
    }
}

//更新阶段
function updateStage(id, msg) {
    if (msg == '---') {
        hiddenStage(id)
    }
    else if (msg == '合格') {
        showStage(id)
        $(id).addClass('ok')
    } else if (msg == '不合格') {
        showStage(id)
        $(id).addClass('no')
    }
    $(id).text(msg);
}

//更新阶段
function updateCurrentStage(time, name) {
    $("#stage_time").text(time);
    $("#stage_name").text(name + "剩余");
}

//阶段隐藏
function hiddenStage(id) {
    $(id + "Row").removeClass('layui-show')
    $(id + "Row").addClass('layui-hide')
}

//阶段显示
function showStage(id) {
    $(id + "Row").removeClass('layui-hide')
    $(id + "Row").addClass('layui-show')
}

//压力表盘配置
function pressureChartOptions(type) {
    var option = gaugeChartOptions();
    if (type == "main") {
        option['series'][0]['data'] = [{ "value": 10.5, "name": "近端压力" }]
    } else if (type == "remote") {
        option['series'][0]['data'] = [{ "value": 0, "name": "远端压力" }]
    }

    option['series'][0]['detail']['formatter'] = '{value} Mpa'
    option['series'][0]['detail']['color'] = "#16b777"
    option['series'][0]['itemStyle']['color'] = "#16b777"
    return option;
}
//仪表板配置
function gaugeChartOptions() {
    var option = {
        series: [
            {
                type: 'gauge',
                center: ['50%', '85%'],
                startAngle: 180,
                endAngle: 0,
                min: 0,
                max: 30,
                itemStyle: {
                    color: '#FFAB91'
                },
                progress: {
                    show: true,
                    width: 10
                },
                pointer: {
                    show: false
                },
                axisLine: {
                    lineStyle: {
                        width: 10,
                    }
                },
                axisTick: {
                    distance: -30,
                    splitNumber: 5,
                    lineStyle: {
                        width: 2,
                        color: '#999'
                    }
                },
                splitLine: {
                    distance: -37,
                    length: 14,
                    lineStyle: {
                        width: 3,
                        color: '#999'
                    }
                },
                axisLabel: {
                    distance: -20,
                    color: '#999',
                    fontSize: 12
                },
                anchor: {
                    show: false
                },
                title: {
                    show: true,
                    color: "#fff",
                    fontSize: 14
                },
                detail: {
                    valueAnimation: true,
                    width: '20%',
                    lineHeight: 20,
                    borderRadius: 8,
                    offsetCenter: [0, '-15%'],
                    fontSize: 20,
                    fontWeight: 'bolder',
                    formatter: '{value}',
                    color: 'inherit',
                    textStyle: {
                        fontSize: 20,
                    }
                }
            }
        ]
    };
    return option;
}

var chartImageData;
function lineChartOption() {
    var now = moment(moment().format("YYYY-MM-DD HH:mm") + ":00");
    var startDate = now.format("YYYY-MM-DD HH:mm:ss");
    var endDate = now.add(5, 'm').format("YYYY-MM-DD HH:mm:ss");
    var xAxis = xAxisOption(startDate);
    //xAxis["max"] = endDate;
    var option = {
        tooltip: {
            trigger: "axis",
        },
        /*
        <svg t="1735634587773" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4784" width="35" height="35"><path d="" fill="#ffffff" p-id="4785"></path></svg>
        
        */
        toolbox: {
            iconStyle: {//想全部变色就放在外边，想部分按钮就放在方法里
	            borderColor: "#ffffff",
	          },
            show: true,
            right: "10%",
            feature: {
                myRealtime: { // 必须以my开头,不然不会显示
                    show: true,
                    title: '实时',
                    icon: 'path://M680.106667 774.165333c4.266667 0 7.936 1.536 11.029333 4.650667a15.061333 15.061333 0 0 1 4.650667 11.008 15.061333 15.061333 0 0 1-4.650667 11.029333l-33.557333 33.557334c11.605333 10.773333 24.746667 19.093333 39.445333 24.96a122.218667 122.218667 0 0 0 45.781333 8.832 123.221333 123.221333 0 0 0 61.226667-15.914667 123.477333 123.477333 0 0 0 45.546667-43.84c1.792-2.773333 6.122667-12.330667 12.992-28.650667 1.28-3.754667 3.754667-5.632 7.338666-5.632h47.018667c2.133333 0 3.968 0.768 5.504 2.325334a7.530667 7.530667 0 0 1 2.090667 7.210666c-10.453333 43.754667-32.32 79.232-65.621334 106.410667-33.322667 27.178667-72.32 40.789333-117.077333 40.789333a183.466667 183.466667 0 0 1-69.184-13.482666 186.922667 186.922667 0 0 1-59.626667-38.442667l-31.573333 31.573333a15.061333 15.061333 0 0 1-11.029333 4.672 15.061333 15.061333 0 0 1-11.029334-4.650666 15.061333 15.061333 0 0 1-4.650666-11.029334v-109.717333c0-4.245333 1.557333-7.893333 4.650666-11.008a15.061333 15.061333 0 0 1 11.029334-4.650667h109.696zM160 127.978667l0.128 493.76 205.845333-215.573334a32 32 0 0 1 43.584-2.496l2.474667 2.282667 100.501333 103.146667L830.698667 190.72a32 32 0 0 1 47.466666 42.794667l-2.197333 2.432-341.077333 341.333333a32 32 0 0 1-43.114667 1.962667l-2.432-2.24-100.010667-102.634667-229.184 240 0.042667 149.632h330.730667v64H138.88c-23.552 0-42.666667-19.114667-42.666667-42.666667l-0.085333-180.757333a32.192 32.192 0 0 1 0-5.824L96 128h64z m582.826667 426.752c23.829333 0 46.997333 4.522667 69.546666 13.589333a189.738667 189.738667 0 0 1 59.989334 38.336l31.829333-31.594667a15.061333 15.061333 0 0 1 11.029333-4.650666c4.245333 0 7.914667 1.536 11.008 4.650666a15.061333 15.061333 0 0 1 4.672 11.008v109.717334a15.061333 15.061333 0 0 1-4.672 11.029333 15.061333 15.061333 0 0 1-11.008 4.650667h-109.717333a15.061333 15.061333 0 0 1-11.029333-4.650667 15.061333 15.061333 0 0 1-4.650667-11.029333c0-4.245333 1.557333-7.914667 4.650667-11.008l33.813333-33.813334c-24.170667-22.357333-52.672-33.536-85.482667-33.536a123.221333 123.221333 0 0 0-61.226666 15.914667 123.477333 123.477333 0 0 0-45.546667 43.84c-1.792 2.773333-6.122667 12.309333-12.970667 28.650667-1.322667 3.754667-3.754667 5.632-7.36 5.632h-48.725333a7.530667 7.530667 0 0 1-5.504-2.346667 7.530667 7.530667 0 0 1-2.346667-5.504v-1.706667c10.624-43.733333 32.661333-79.232 66.133334-106.410666 33.472-27.178667 72.661333-40.768 117.546666-40.768z',
                    onclick: function () {
                        start = 50;
                    }
                },
                myAll: { // 必须以my开头,不然不会显示
                    show: true,
                    title: '全部',
                    icon: 'path://M170.666667 106.666667l0.192 736H906.666667v64H149.546667c-23.552 0-42.666667-19.093333-42.666667-42.666667L106.666667 106.666667h64z m686.506666 454.144l13.653334 16.362666a21.333333 21.333333 0 0 1-2.666667 30.058667l-171.157333 143.146667a21.333333 21.333333 0 0 1-21.546667 3.477333l-229.973333-91.285333-113.834667 94.997333a21.333333 21.333333 0 0 1-30.037333-2.709333l-13.653334-16.362667a21.333333 21.333333 0 0 1 2.688-30.058667l133.312-111.274666a21.333333 21.333333 0 0 1 21.546667-3.456l229.930667 91.264 151.68-126.826667a21.333333 21.333333 0 0 1 30.037333 2.666667z m-1.621333-417.962667l16.896 13.013333a21.333333 21.333333 0 0 1 3.925333 29.888L685.802667 433.706667a21.333333 21.333333 0 0 1-20.202667 8.085333l-226.794667-35.413333-150.186666 222.357333a21.333333 21.333333 0 0 1-27.477334 7.018667l-2.133333-1.28-17.685333-11.946667a21.333333 21.333333 0 0 1-5.738667-29.610667l165.354667-244.821333a21.333333 21.333333 0 0 1 20.992-9.130667L650.453333 374.613333l175.146667-227.882666a21.333333 21.333333 0 0 1 29.930667-3.904z',
                    onclick: function () {
                        start = 100;
                    }
                },
                mySave: { // 必须以my开头,不然不会显示
                    show: true,
                    title: '保存',
                    icon: 'path://M868.100096 742.600704l-0.049152 0L216.246272 742.600704l-0.049152 0c-13.98784 0-25.327616 11.33568-25.327616 25.352192 0 13.993984 11.360256 25.327616 25.327616 25.327616l0.049152 0 651.804672 0 0.049152 0c13.996032 0 25.33376-11.333632 25.33376-25.327616C893.431808 753.936384 882.096128 742.600704 868.100096 742.600704L868.100096 742.600704 868.100096 742.600704M523.15136 688.433152c4.728832 4.757504 11.237376 7.733248 18.47296 7.733248l0 0 0 0c7.231488 0 13.740032-2.951168 18.42176-7.757824l314.836992-314.83904c4.732928-4.704256 7.714816-11.214848 7.7312-18.395136 0-14.342144-11.712512-25.9584-25.972736-25.9584-7.213056-0.02048-13.694976 2.930688-18.376704 7.636992L567.578624 607.51872 567.578624 117.52448c-0.024576-0.026624-0.024576-0.026624-0.024576-0.0512 0.024576-14.344192-11.59168-25.980928-25.901056-25.980928-14.348288 0-25.960448 11.634688-25.960448 25.980928 0 0 0 0.024576 0.024576 0.0512l0 489.967616L245.055488 336.826368c-4.683776-4.704256-11.2128-7.6288-18.374656-7.60832-14.342144-0.02048-25.954304 11.614208-26.005504 25.9072 0 7.20896 2.951168 13.768704 7.684096 18.423808L523.15136 688.433152 523.15136 688.433152 523.15136 688.433152M523.15136 688.433152 523.15136 688.433152z',
                    onclick: function () {
                        getChartImageData()
                        let aLink = document.createElement('a');
                        let blob = base64ToBlob(chartImageData);
                        let evt = document.createEvent("HTMLEvents");
                        evt.initEvent("click", true, true);
                        aLink.download = "line.png";
                        aLink.href = URL.createObjectURL(blob);
                        aLink.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
                    }
                },
            },
        },
        dataZoom: [{
            type: 'slider',
            realtime: true,
            top: "425px"
        }],
        xAxis: xAxis,
        yAxis: {
            min: 0,
            max: 30,
            axisLabel: {
                color: "#ffffff"
            }
        }
    };
    return option;
}

function getChartImageData() {
    chartImageData = pressureChart.getDataURL({
        type: "png",
        pixelRatio: 2,
        backgroundColor: "#c2c2c2",
      });
}

function base64ToBlob(code) {
    let parts = code.split(';base64,');
    let contentType = parts[0].split(':')[1];
    let raw = window.atob(parts[1]);
    let rawLength = raw.length;

    let uInt8Array = new Uint8Array(rawLength);

    for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
    }
    return new Blob([uInt8Array], { type: contentType });
}

function xAxisOption(startDate) {
    var data = {
        type: 'time',
        name: '时间',
        min: startDate,
        axisLabel: {
            formatter: '{MM}-{dd} {HH}:{mm}:{ss}',
            show: true,
            showMinLabel: true,
            showMaxLabel: true,
            width: 60,
            overflow: 'break',
            color: "#ffffff"
        }
    };
    return data;
}

//数据库状态
var dataBaseState = false
//更新数据库状态
function setDataBaseState(state) {
    if (state == 1) {
        dataBaseState = true;
    }
}

//消息
function layerMessage(msg, icon) {
    var a = arguments[0] ? arguments[0] : '';
    var b = arguments[1] ? arguments[1] : 7;
    if (a.length > 0) {
        layer.msg(msg, { icon: b, shade: 0.3, time: 900 });
    }
}

//loading
var loadIndex;
function layerLoading(msg) {
    loadIndex = layer.msg(msg, { icon: 16, shade: 0.3, time: 0 });
}
//loading结束
function endLayerLoading() {
    layer.close(loadIndex);
}

//关闭按钮
$("#minimize").on('click', function () {
    window.formium.postMessage("FormState", "minimize");
})
//关闭按钮
$("#close").on('click', function () {
    var str = "您确定要关闭采集程序吗？";
    if (startCollectState == true) {
        str = "正在采集，您确定要关闭采集程序吗？";
    }
    layer.confirm(str, { icon: 3 }, function () {
        window.formium.postMessage("FormState", "close");
    });
})

//当前时间
nowTime();
setInterval(() => {
    nowTime();
}, 1000);
//当前时间
function nowTime() {
    $("#time").text(moment().format("HH:mm:ss"));
    $("#date").text(moment().format("YYYY-MM-D"));
}
var messageData = [];
var messageTable;
layui.use(["table"], function () {
    var table = layui.table;
    messageTable = table.render({
        elem: '#message',
        height: '#messagebox',
        cols: [[
            { field: 'time', title: '时间', width: "49%", unresize: true },
            { field: 'content', title: '内容', width: "50%", unresize: true }
        ]],
        data: messageData
    });
})

function addMessage(msg) {
    if (messageData.length > 3) {
        messageData.pop();
    }
    var data = { "time": moment().format("YYYY-MM-D HH:mm:ss"), "content": msg };
    messageData.unshift(data);
    console.log(messageData)
    messageTable.reload("message", {
        data: messageData
    });
}
